﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using MasterDetailTemplate.Models;
using MasterDetailTemplate.Services;

namespace MasterDetailTemplate.ViewModels
{
    /// <summary>
    /// 菜单ViewModel。
    /// By XJ
    /// </summary>
    public class MenuPageViewModel : ViewModelBase
    {
        /******** 构造函数 ********/

        /// <summary>
        /// 根导航服务。
        /// </summary>
        private IRootNavigationService rootNavigationService;

        /// <summary>
        /// 菜单页ViewModel。
        /// </summary>
        /// <param name="rootNavigationService">根导航服务。</param>
        public MenuPageViewModel(IRootNavigationService rootNavigationService)
        {
            this.rootNavigationService = rootNavigationService;

            Messenger.Default.Register<RootNavigationMessage>(this,
                message => SelectedMenuItem =
                    MenuItem.GetMenuItem(message.PageKey));
        }

        /******** 绑定属性 ********/

        /// <summary>
        /// 当前菜单项。
        /// </summary>
        public MenuItem SelectedMenuItem
        {
            get => _selectedMenuItem;
            set => Set(nameof(SelectedMenuItem), ref _selectedMenuItem, value);
        }

        /// <summary>
        /// 当前菜单项。
        /// </summary>
        private MenuItem _selectedMenuItem;

        /******** 绑定命令 ********/

        /// <summary>
        /// 菜单项点击命令。
        /// </summary>
        public RelayCommand<MenuItem> MenuItemTappedCommand =>
            _menuItemTappedCommand ?? (_menuItemTappedCommand =
                new RelayCommand<MenuItem>(async menuItem =>
                    await MenuItemTappedCommandFunction(menuItem)));

        /// <summary>
        /// 菜单项点击命令。
        /// </summary>
        private RelayCommand<MenuItem> _menuItemTappedCommand;

        public async Task MenuItemTappedCommandFunction(MenuItem menuItem) =>
            await rootNavigationService.NavigateToAsync(menuItem.PageKey);
    }

}